import UserModel from "../models/user";
import Jwt from '../utils/Jwt'
import {Document} from "mongoose";
import * as crypto from "crypto"

const jwt = new Jwt()

function md5(str) {
    const c = crypto.createHash("md5")
    return c.update(str).digest("hex")
}

class Auth {
    async login(ctx) {
        const {account, password} = ctx.request.body

        const res: any = await UserModel.findOne({account})
        let response
        if (res != null) {
            if (res.password === md5(password)) {
                response = {
                    success: true,
                    data: {
                        token: await jwt.generateToken(account),
                    },
                    msg: "登录成功！"
                }
            } else {
                response = {
                    success: false,
                    msg: "账号或密码有误！"
                }
            }
        } else {
            response = {
                success: false,
                msg: "账号不存在！"
            }
        }
        ctx.body = response

    }

    async register(ctx) {
        const {account, password} = ctx.request.body
        const res = await UserModel.findOne({account})
        if (res) {
            return ctx.body = {success: false, msg: "账户已存在"}
        } else {
            await UserModel.create(new Document({account, password: md5(password)}))
            return ctx.body = {success: true, msg: "注册成功！"}
        }
    }
}

module.exports = new Auth()
